package com.jyxd.web.filter;

import com.jyxd.web.data.user.User;
import com.jyxd.web.util.UUIDUtil;
import org.slf4j.MDC;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "sessionFilter", urlPatterns = {"/*"})
public class SessionFilter implements Filter {

    //标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
    String NO_LOGIN = "您还未登录";

    //swagger所需要非认证的url
    private static final String NOT_FILTER_STR = "/login|/photoUpload|/img/|/loginOut|/api/login|" +
            "/importExcel|/api/upload/pic|/api/deviceGis/add|user|/doc.html|swagger|.ico|.js|.css|/v2/api-docs";


    private static List<String> NOTFILTER_ARRAY;

    public SessionFilter() {
        NOTFILTER_ARRAY = Arrays.asList(NOT_FILTER_STR.split("\\|"));
    }


    //不需要登录就可以访问的路径(比如:注册登录等)
    String[] includeUrls = new String[]{"/login", "/user/login", "/download/plugin", "/user/logout", "/getHisMessage", "/getHisPatientMessage",
            "/patientRegistry", "/hip", "/cxfServlet/webservice", "/jyxd/hisService","/webApi", "/outputAmount/analysisData"};


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        //response.setHeader("Access-Control-Max-Age", "3600");
        //response.setHeader("Access-Control-Allow-Headers", ":x-requested-with,content-type");
        response.setHeader("Access-Control-Allow-Headers", "*");
        //((HttpServletResponse)servletResponse).setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        MDC.put("traceID", UUIDUtil.getUUID());
        if(session !=null) {
            User user = (User)session.getAttribute("user");
            if(user !=null) {
                MDC.put("userID",user.getId());
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

}
